import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types'
import { authAPI } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string>('')

  // 从localStorage恢复状态
  const initFromStorage = () => {
    try {
      const savedToken = localStorage.getItem('token')
      const savedUser = localStorage.getItem('user')

      console.log('从存储恢复 token:', savedToken ? savedToken.substring(0, 20) + '...' : 'null')

      if (savedToken) {
        token.value = savedToken
      }
      if (savedUser) {
        user.value = JSON.parse(savedUser)
      }
    } catch (error) {
      console.error('从存储恢复状态失败:', error)
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  }

  // 登录
  const login = async (loginForm: { email: string; password: string }) => {
    console.log('开始登录:', loginForm.email)

    // 调用登录接口
    const response = await authAPI.login(loginForm)
    console.log('登录响应 token:', response.token.substring(0, 20) + '...')

    // 先保存 token 到 localStorage 和 store
    token.value = response.token
    localStorage.setItem('token', response.token)
    console.log('token 已保存到 localStorage')

    // 然后获取用户信息
    await getProfile()

    console.log('登录流程完成')
  }

  // 注册
  const register = async (registerForm: { email: string; password: string; nickname: string }) => {
    await authAPI.register(registerForm)
  }

  // 获取用户信息
  const getProfile = async () => {
    try {
      console.log(
        '开始获取用户信息，当前 token:',
        token.value ? token.value.substring(0, 20) + '...' : 'null',
      )

      const userInfo = await authAPI.getProfile()
      console.log('获取到的用户信息:', userInfo)

      user.value = userInfo
      localStorage.setItem('user', JSON.stringify(userInfo))
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    console.log('退出登录')
    user.value = null
    token.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 检查登录状态
  const checkAuth = async (): Promise<boolean> => {
    const savedToken = localStorage.getItem('token')
    console.log(
      '检查认证状态，存储的 token:',
      savedToken ? savedToken.substring(0, 20) + '...' : 'null',
    )

    if (!savedToken) {
      return false
    }

    // 更新当前 token
    token.value = savedToken

    try {
      await getProfile()
      return true
    } catch (error) {
      console.error('认证检查失败:', error)
      logout()
      return false
    }
  }

  // 初始化
  initFromStorage()

  return {
    user,
    token,
    login,
    register,
    getProfile,
    logout,
    checkAuth,
  }
})
